package org.darcy.youchat.activity.file;

import android.content.Intent;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;

import com.netease.nimlib.sdk.msg.attachment.FileAttachment;
import com.netease.nimlib.sdk.msg.model.IMMessage;

import org.darcy.youchat.R;
import org.darcy.youchat.activity.BaseActivity;
import org.darcy.youchat.databinding.ActivityFilePreviewBinding;
import org.darcy.youchat.utils.FileIconUtils;
import org.darcy.youchat.utils.FileOpenUtils;
import org.darcy.youchat.utils.FileUtils;
import org.darcy.youchat.utils.MimeTypeUtils;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 * 文件预览
 */
public class FilePreviewActivity extends BaseActivity {

    private ActivityFilePreviewBinding binding;
    private FileAttachment mFa;

    @Override
    public void init() {
        Intent mIntent = getIntent();
        IMMessage mMessage = (IMMessage) mIntent.getSerializableExtra("message");
        if (mMessage == null) {
            interrupt();
            return;
        }
        mFa = (FileAttachment) mMessage.getAttachment();
    }

    @Override
    public void initView() {
        binding = ActivityFilePreviewBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setSupportActionBar(binding.mToolbar.toolbar);
        String titleName = "文件预览";
        getSupportActionBar().setTitle(titleName);
        binding.mToolbar.toolbar.setNavigationIcon(R.mipmap.ic_back);

        binding.ivPic.setImageResource(FileIconUtils.getFileIconResId(mFa.getExtension()));
        binding.tvName.setText(mFa.getDisplayName());
        binding.pbFile.setVisibility(View.GONE);
        binding.btnOpen.setVisibility(View.VISIBLE);
        if (TextUtils.isEmpty(mFa.getPath())) {
            binding.btnOpen.setText("下载");
        } else {
            binding.btnOpen.setText("其他应用打开");
        }
    }

    @Override
    public void initData() {
    }

    @Override
    public void initListener() {
        binding.btnOpen.setOnClickListener(v -> {
            if (binding.btnOpen.getText().equals("下载")) {
                downloadFile();
            } else {
                //打开文件
                FileOpenUtils.openFile(FilePreviewActivity.this, mFa.getPath(), MimeTypeUtils.getMimeType(mFa.getDisplayName()));
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    //下载文件
    private void downloadFile() {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .url(mFa.getUrl())
                .build();
        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                binding.ivPic.setImageResource(R.mipmap.default_img_failed);
                binding.tvName.setText("文件已过期或已被清理");
                binding.pbFile.setVisibility(View.GONE);
                binding.btnOpen.setVisibility(View.GONE);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws FileNotFoundException {
                binding.ivPic.setImageResource(FileIconUtils.getFileIconResId(mFa.getExtension()));
                binding.tvName.setText(mFa.getDisplayName());
                binding.pbFile.setVisibility(View.GONE);
                binding.btnOpen.setVisibility(View.VISIBLE);
                if (TextUtils.isEmpty(mFa.getPath())) {
                    binding.btnOpen.setText("下载");
                } else {
                    binding.btnOpen.setText("其他应用打开");
                }
                //保存文件
                InputStream inputStream = Objects.requireNonNull(response.body()).byteStream();
                File target = new File(FileUtils.getDirFromPath(mFa.getPathForSave()), FileUtils.getFileNameFromPath(mFa.getPathForSave()));
                FileOutputStream fileOutputStream = new FileOutputStream(target);
                try {
                    byte[] buffer = new byte[2048];
                    int len;
                    while ((len = inputStream.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, len);
                    }
                    fileOutputStream.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
